package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 东莞呵呵
 * Date:2022-10-04
 * Time:20:20
 */
public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    /*
     1、读取客户端发来的请求
     2、根据请求计算响应
     3、响应写回客户端
     */
    //启动服务器
    public void start() throws IOException {

        //1、读取客户端发来的请求
        DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
        socket.receive(requestPacket);//输出型参数
        //把DatagramPacket解析成为一个String(从0下标，到getLength())
        String request = new String(requestPacket.getData(), 0,
                requestPacket.getLength(), "UTF-8");

        //2、根据请求计算响应
        String response = process(request);

        // 3、响应写回客户端,getSocketAddress指定了IP和端口。
        DatagramPacket responsePacket = new DatagramPacket(response .getBytes(),
                response.getBytes().length, requestPacket.getSocketAddress());//字符的个数，如果直接用length的话就是字节的个数
        socket.send(responsePacket);
    }

    //我们写的是回显伏虎，响应和请求一样
    //实际上对于一个真实的服务器，这个过程是复杂的，可能需要几万行的代码
    protected String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}
